import env from "@/config";


export class WsEventCallback {
    constructor() {

    }

    //连接完成回调
    onConnComplete(res, ws) {

    }

    //连接错误回调
    onConnError(res, ws) {

    }

    //消息读取回调
    onRead(res, ws) {

    }

    //连接建立回调
    onOpen(res, ws) {

    }

    //连接关闭回调
    onClose(res, ws) {

    }
}

export class WsSocket {
    constructor(wsBizCallback) {
        this.socketMsgQueue = [];
        this.socketOpen = false;
        this.socketTask = null;
        this.needRetry = true;
        this.wsEventCallback = wsBizCallback;
    }

    //连接服务器
    connServer() {
        let that = this;
        this.socketTask = uni.connectSocket({
            url: env.socketUrl,
            complete: function (res) {
                that.wsEventCallback.onConnComplete(res, that);
            }
        });

        this.socketTask.onOpen((res) => {
            that.socketOpen = true;
            that.wsEventCallback.onOpen(res, that);
            for (let i = 0; i < that.socketMsgQueue.length; i++) {
                that.sendSocketMessage(that.socketMsgQueue[i]);
            }
            that.socketMsgQueue = [];
        });

        this.socketTask.onMessage((res) => {
            this.wsEventCallback.onRead(res, this);
        });


        this.socketTask.onError((res) => {
            this.socketOpen = false;
            this.wsEventCallback.onConnError(res, this);
        });

        this.socketTask.onClose((res) => {
            this.socketOpen = false;
            this.wsEventCallback.onClose(res, this);
        });
    }

    //发送消息
    sendSocketMessage(data, cb) {
        if (this.socketOpen) {
            this.socketTask.send({
                data: data,
                complete: function (res) {
                    if (typeof cb == "function") {
                        cb(res);
                    }
                }
            });
        } else {
            console.log("连接已关闭，但还在发送消息")
        }
    }

    //关闭连接
    closeConnect() {
        //主动关闭连接后不再进行重试
        this.needRetry = false;
        console.log("客户端主动关闭连接");
        this.socketTask.close();
    }
}

function isArrayBuffer(obj) {
    return Object.prototype.toString.call(obj) === '[object ArrayBuffer]'
}

